package io.boot.modules.activiti.service.impl;

import io.boot.common.utils.PageUtils;
import io.boot.modules.activiti.dto.UpComing;
import io.boot.modules.activiti.service.UpComingService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author kyson
 * @date 2020/04/20 11:34
 */
@Service("UpComingServiceImpl")
public class UpComingServiceImpl implements UpComingService {

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;


    @Override
    public PageUtils queryPage(Map<String, Object> params, String userName) {
        Integer page=Integer.valueOf(params.get("page").toString());
        Integer limit=Integer.valueOf(params.get("limit").toString());
        TaskQuery taskQuery = taskService.createTaskQuery();
        taskQuery.taskAssignee(userName);
        List<Task> tasks = taskQuery.listPage((page - 1) * limit, limit);
        List<UpComing>  upComingList=new ArrayList<>();
        for (Task task:tasks) {
            UpComing upComing=new UpComing();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).includeProcessVariables().singleResult();
//            upComing.setReferee(processInstance.getProcessVariables().get("createBy")!=null?processInstance.getProcessVariables().get("createBy").toString():"");
            upComing.setId(task.getId());
            upComing.setUpUser(task.getAssignee());
            upComing.setCreateTime(task.getCreateTime());
            List<String> processDefinitionIds= Arrays.asList(task.getProcessDefinitionId().split(":"));
            upComing.setProcessName(processDefinitionIds.get(0));
            upComing.setProcessVersion(processDefinitionIds.get(1));
            upComing.setUpName(task.getName());
            upComing.setType(task.isSuspended());
            upComing.setClaimTime(task.getCreateTime());
            upComing.setInstanceId(task.getProcessInstanceId());
            upComingList.add(upComing);
        }
        PageUtils pages =new PageUtils(upComingList,Integer.valueOf(taskQuery.count()+""),page,limit);
        return pages;
    }
}
